package com.imooc.common.aop;

import com.imooc.common.constant.CommonConstant;
import com.imooc.common.exception.SellerAuthException;
import com.imooc.common.utils.CookieUtil;
import org.apache.commons.lang.StringUtils;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

@Aspect
@Component
public class SellerAuyhAspect {

    @Autowired
    RedisTemplate redisTemplate;

    @Pointcut("execution(public * com.imooc.controller.Seller*.*(..))" +
            "&& !execution(public * com.imooc.controller.SellerUserController.*(..))")
    public void verify() {

    }

    @Before("verify()")
    public void doVerify() {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();

        Cookie cookie = CookieUtil.getCookie(request, CommonConstant.TOKEN);
        if (cookie == null){
            throw new SellerAuthException();
        }

        String value = (String)redisTemplate.opsForValue().get(String.format(CommonConstant.REDIS_TOKEN_PREFIX, cookie.getValue()));
        if (StringUtils.isBlank(value)){
            throw new SellerAuthException();
        }
    }
}
